package com.bitter.paysdkdemo;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.bitter.paysdk.OnPayListener;
import com.bitter.paysdk.PayAgent;
import com.bitter.paysdk.PayInfo;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity implements
        View.OnClickListener {

    private ProgressDialog progressDialog;
    private Button aliPayBtn, wxPayBtn, upPayBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化 支付组件
        PayAgent payAgent = PayAgent.getInstance();
        payAgent.setDebug(true);

//		payAgent.initAliPayKeys(partnerId, sellerId, privateKey, publicKey)
//		payAgent.initWxPayKeys("wx5e0d459762737b8c", "1264771501", "HP22EVMVEW7Z6ZBNZ56MKSB2Y3LP2T4H");
//		payAgent.initWxPayKeys("wx79e95c3cb4556117", "1264869501", "PUGMB239LWENZEDMW9RTTDWRZT83JWYL");

//		初始化 银联支付 所需的 验签 参数
//		payAgent.initUpPayKeys(PublicKeyPMModulus, publicExponent, PublicKeyProductModulus);

        payAgent.initPay(this);

        initViews();
    }

    private void initViews() {
        progressDialog = new ProgressDialog(MainActivity.this);

        aliPayBtn = (Button) findViewById(R.id.alipay);
        wxPayBtn = (Button) findViewById(R.id.weichatpay);
        upPayBtn = (Button) findViewById(R.id.uppay);

        aliPayBtn.setOnClickListener(this);
        wxPayBtn.setOnClickListener(this);
        upPayBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.alipay:
//                String str = "alipay_sdk=alipay-sdk-java-dynamicVersionNo" +
//                        "&app_id=2017021705713581" +
//                        "&biz_content=%7B%22body%22%3A%22%E6%94%AF%E4%BB%98%22%2C%22out_trade_no%22%3A%22DEPOSIT20180627173658161WOevJdXF%22%2C%22product_code%22%3A%22NOProduct%22%2C%22subject%22%3A%22%E6%AD%A3%E5%9C%A8%E6%94%AF%E4%BB%98%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D" +
//                        "&charset=utf-8" +
//                        "&format=json" +
//                        "&method=alipay.trade.app.pay" +
//                        "&notify_url=http%3A%2F%2F118.178.240.207%3A9090%2Fmobility%2Falipay%2Fnotify.do" +
//                        "&sign=sYDE9vFyJTs5oxXIGOJQiLvZ7jFTpYBw8GJhg1IO%2BNhzgcTiY8Kywwu3GQR%2F8Ajc9ez8XDD3A3gbaJ3LA1DnLiTDth9fbrecICs%2Fph9DlCoGTV4Oe767c%2BO7vMhZUmNJZ9Ak0D7s3MpZgZQ9syPqnsnffitKavtnhTT%2FZPM2xPS3ey%2FFYvMulsW8NFJPtmPCaA0NNV8Mrtz5seWK%2FgXtwxGnu5pskqU8h5PGKlhRw4peMXlR9Zan8CENL3cOsR74qB8NDOv9PEqnXHvNSEfq9SFz8Yn6K7D3ogNryHRKPbRXTdoPxCHChPowBd%2FgcYzOubZVbfrW00OyrgIFkHG7%2BQ%3D%3D" +
//                        "&sign_type=RSA2" +
//                        "&timestamp=2018-06-27+17%3A36%3A58" +
//                        "&version=1.0" +
//                        "&sign=sYDE9vFyJTs5oxXIGOJQiLvZ7jFTpYBw8GJhg1IO%2BNhzgcTiY8Kywwu3GQR%2F8Ajc9ez8XDD3A3gbaJ3LA1DnLiTDth9fbrecICs%2Fph9DlCoGTV4Oe767c%2BO7vMhZUmNJZ9Ak0D7s3MpZgZQ9syPqnsnffitKavtnhTT%2FZPM2xPS3ey%2FFYvMulsW8NFJPtmPCaA0NNV8Mrtz5seWK%2FgXtwxGnu5pskqU8h5PGKlhRw4peMXlR9Zan8CENL3cOsR74qB8NDOv9PEqnXHvNSEfq9SFz8Yn6K7D3ogNryHRKPbRXTdoPxCHChPowBd%2FgcYzOubZVbfrW00OyrgIFkHG7%2BQ%3D%3D";
                String str = "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2017052707365732&biz_content=%7B%22body%22%3A%22%E6%94%AF%E4%BB%98%22%2C%22out_trade_no%22%3A%22RECHARG20180628164029154ySLjpdoN%22%2C%22product_code%22%3A%22NOProduct%22%2C%22subject%22%3A%22%E6%AD%A3%E5%9C%A8%E6%94%AF%E4%BB%98%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fapp.etbike.net%2Fmobility%2Falipay%2Fnotify.do&sign=LZN33Oq1%2BqAVniUoQb9SCgYAS9asUDUFGE1sBERAzbPRje1zvWJRldM%2FYQBK6QD%2BTJTaQFXyYoRSXweF0gj7ACmt55%2Btin8lnS46TDQdz9EUs5eG1BP%2BnCb1rZVJyoT72KdvGbT%2Fv6f7yMjy0NwqqbHvYyCqBV%2FwWeJ3M%2FS1e1S8gyEtvEYJHV4d2pJjl%2BKgFjFO29cPDoMfWqAZvngbbzvdeuypAc0c4T%2BpL%2BsaSBREQ7PLflEMz%2BK3Kj1LhizhL4UWDqQGJuv0YGSHmZiZLPjIztaDpa3OUdRpsOeLwYXj0PR5x31mXjK6AhsKl84Ok4B1XPmbCb6SSjyYBh%2FOiw%3D%3D&sign_type=RSA2&timestamp=2018-06-28+16%3A40%3A29&version=1.0";
                PayInfo payInfo = new PayInfo();
                payInfo.setZfbOrderInfoString(str);
                testPay(PayAgent.PayType.ALIPAY, payInfo);
                break;

            case R.id.weichatpay:
                PayInfo info = new PayInfo();
                info.setWxApp_id("wxf2e9d00e12ae069f");
                info.setWxPartnerid("1446292102");
                info.setWxPackageValue("Sign=WXPay");
                info.setWxPrepayId("wx0216430529165648b08694fa0840896724");
                info.setWxNonceStr("6R9L5fdYSC2H");
                info.setWxTimeStamp("1530520985");
                info.setWxSign("E7BFEB86967B5BFB27185887117ACC7F");
                testPay(PayAgent.PayType.WECHATPAY, info);
                break;

            case R.id.uppay:
                //requestTestOrderNo();
                //需更新测试
                Toast.makeText(getApplicationContext(), "更新中...", Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
        }

    }

    /**
     * 网银 请求支付订单号
     *
     * @return void
     */
    private void requestTestOrderNo() {

        new AsyncTask<String, Integer, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progressDialog.setTitle("请求订单中...");
                progressDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {

                String tn = null;
                InputStream is;
                try {

                    String url = "http://202.101.25.178:8080/sim/gettn";

                    URL myURL = new URL(url);
                    URLConnection ucon = myURL.openConnection();
                    ucon.setConnectTimeout(50000);
                    is = ucon.getInputStream();
                    int i = -1;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while ((i = is.read()) != -1) {
                        baos.write(i);
                    }

                    tn = baos.toString();
                    is.close();
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.i(getClass().getName(), "response :" + tn);

                return tn;
            }


            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                progressDialog.dismiss();

                // 获取到 订单后，调起支付
                PayInfo inf = new PayInfo();
                inf.setYlOrderNo(result);
                try {
                    testPay(PayAgent.PayType.UPPAY, inf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }.execute();


    }

    /**
     * 调起 支付平台
     *
     * @param payType
     * @param payInfo
     * @return void
     */
    private void testPay(PayAgent.PayType payType, PayInfo payInfo) {

        PayAgent.getInstance().onPay(payType, this, payInfo,
                new OnPayListener() {
                    @Override
                    public void onStartPay(PayAgent.PayType payType) {
                        progressDialog.setTitle("支付中...");
                        progressDialog.show();
                    }
                    @Override
                    public void onPaySuccess(PayAgent.PayType payType, String orderNo, Object data) {
                        Toast.makeText(MainActivity.this, "支付成功！", Toast.LENGTH_SHORT).show();
                        String dataStr = (payType == PayAgent.PayType.WECHATPAY?((Bundle)data).toString():(String)data);
                        Log.e(getClass().getName(), "--orderNo:" + orderNo + "--data:" + dataStr);
                        if (null != progressDialog) {
                            progressDialog.dismiss();
                        }
                    }
                    @Override
                    public void onPayFail(PayAgent.PayType payType, String code, String msg) {
                        Toast.makeText(MainActivity.this,"支付失败:"+
                                "code:" + code + "msg:" + msg, Toast.LENGTH_SHORT).show();
                        Log.e(getClass().getName(), "code:" + code + "msg:" + msg);
                        if (null != progressDialog) {
                            progressDialog.dismiss();
                        }
                    }
                });
    }

}
